﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Xml;
using System.IO;

namespace SharpMoney.Library
{
	public class XmlProvider : IExchangeRateProvider
	{
		#region Variables

		private static Hashtable _currencyExchangeRates;
		private string _fileName;

		#endregion

		#region Properties

		private Hashtable CurrencyExchangeRates
		{
			get
			{
				if ( _currencyExchangeRates == null )
					_currencyExchangeRates = CreateTableFromXml();

				return _currencyExchangeRates;
			}
		}

		public string FileName
		{
			get
			{
				return _fileName;
			}
		}

		#endregion

		#region Constructors

		public XmlProvider( string fileName )
		{
			if ( fileName == null )
				throw new ArgumentNullException( "fileName" );

			if ( !File.Exists( fileName ) )
				throw new ArgumentException(
					string.Format( "File [{0}] does not exists.", fileName )
				);

			this._fileName = fileName;
		}

		#endregion

		#region IExchangeRateProvider Members

		public decimal GetRate( string currencyCode )
		{
			return Convert.ToDecimal( CurrencyExchangeRates[currencyCode] );
		}

		#endregion

		#region Private Methods

		private Hashtable CreateTableFromXml()
		{
			Hashtable table = new Hashtable();
			XmlDocument doc = new XmlDocument();

			doc.Load( this.FileName );

			foreach ( XmlNode rate in doc.DocumentElement.ChildNodes )
				table[rate.Attributes["code"].Value] = rate.InnerText;

			return table;
		}

		#endregion
	}
}
